package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"os"
	"strings"
	"time"

	"gopkg.in/goyy/goyy.v0/util/times"
	"gopkg.in/goyy/goyy.v0/util/uuids"
)

var outPutDataJsonSuccess = "dataJsonSuccess.txt"
var datas = make(map[string]Entity)
var succJsonFile *os.File

func Criteriarea() {
	err := ReadLine(dataSuccess, handler)
	log.Println(err)
	//log.Printf("%+v\n", datas)
	//	for _, v := range datas {
	//		log.Printf("%+v\n", v)
	//	}
	//log.Println(len(datas))
	i := 0
	log.Println("3s后准备输出数据到文本")
	time.Sleep(time.Second * 3)
	for _, d := range datas {
		i++
		log.Println("输出第", i, "行数据")
		time.Sleep(time.Second / 1000)
		b, _ := json.Marshal(d)
		succJsonFile.Write(b)
		succJsonFile.Write([]byte("\r\n"))
	}
	succJsonFile.Close()
}

func handler(line string) {
	ent := []Entity{}
	json.Unmarshal([]byte(line), &ent)
	for _, e := range ent {
		if d, ok := datas[e.Pcode]; ok {
			if d.Fullname != "" {
				e.Fullname = fmt.Sprint(d.Fullname, " - ", e.Name)
			} else {
				e.Fullname = fmt.Sprint(e.Name)
			}
			if d.ParentIds != "" {
				e.ParentIds = fmt.Sprint(d.ParentIds, ",", d.Id)
			} else {
				e.ParentIds = fmt.Sprint(d.Id)
			}
			if d.ParentCodes != "" {
				e.ParentCodes = fmt.Sprint(d.ParentCodes, ",", d.Code)
			} else {
				e.ParentCodes = fmt.Sprint(d.Code)
			}
			if d.ParentNames != "" {
				e.ParentNames = fmt.Sprint(d.ParentNames, ",", d.Name)
			} else {
				e.ParentNames = fmt.Sprint(d.Name)
			}
			e.Leaf = 1
			e.ParentId = d.Id
			d.Leaf = 0
			datas[e.Pcode] = d
		} else {
			e.Fullname = fmt.Sprint(e.Name)
			e.ParentId = "root"
			e.ParentIds = "root"
			e.ParentCodes = "000000000000"
			e.ParentNames = "区域"
		}
		e.Id = uuids.New()
		e.Created = times.NowUnixStr()
		e.Modified = times.NowUnixStr()
		e.Grade = len(strings.Split(e.ParentIds, ",")) + 1
		datas[e.Code] = e
	}
}

func ReadLine(fileName string, handler func(string)) error {
	f, err := os.Open(fileName)
	if err != nil {
		errLogger.Println(err)
		return err
	}
	defer f.Close()
	buf := bufio.NewReader(f)
	i := 0
	for {
		time.Sleep(time.Second / 1000)
		line, err := buf.ReadString('\n')
		line = strings.TrimSpace(line)
		handler(line)
		log.Println("第", i, "行")
		i++
		if err != nil {
			errLogger.Println(err)
			if err == io.EOF {
				return nil
			}
			return err
		}
	}
	return nil
}

type Entity struct {
	Id          string `json:"id"`
	Pcode       string `json:"pcode"`
	Name        string `json:"name"`
	Code        string `json:"code"`
	Classify    string `json:"classify"`
	Leaf        int    `json:"leaf"`
	Grade       int    `json:"grade"`
	Fullname    string `json:"fullname"`
	ParentId    string `json:"parentId"`
	ParentIds   string `json:"parentIds"`
	ParentCodes string `json:"parentCodes"`
	ParentNames string `json:"parentNames"`
	Created     string `json:"created"`
	Modified    string `json:"modified"`
}

func init() {
	datas["000000000000"] = Entity{Id: "root", Code: "000000000000", Name: "区域", Leaf: 0, Grade: 1, Created: times.NowUnixStr(), Modified: times.NowUnixStr()}
	succJsonFile, err = os.OpenFile(outPutDataJsonSuccess, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		errLogger.Println(err)
	}
}
